const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
const PORT = 3001;

// 启用CORS，允许所有来源
app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-DashScope-SSE']
}));

// 解析JSON请求体
app.use(express.json({ limit: '10mb' }));

// 添加请求日志
app.use((req, res, next) => {
    console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
    next();
});

// 代理路由
app.post('/api/chat', async (req, res) => {
    try {
        console.log('收到聊天请求，模型:', req.body.model);

        // 检查Authorization头
        if (!req.headers.authorization) {
            return res.status(401).json({
                error: '缺少Authorization头',
                message: '请提供API密钥'
            });
        }

        const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': req.headers.authorization,
                'X-DashScope-SSE': 'disable',
                'User-Agent': 'WebCraft-Chat/1.0'
            },
            body: JSON.stringify(req.body),
            timeout: 30000 // 30秒超时
        });

        const data = await response.json();

        if (!response.ok) {
            console.error('API错误:', response.status, data);
            return res.status(response.status).json({
                error: 'API调用失败',
                status: response.status,
                message: data.message || '未知错误',
                details: data
            });
        }

        console.log('API响应成功，生成内容长度:', data.output?.choices?.[0]?.message?.content?.length || 0);
        res.json(data);
    } catch (error) {
        console.error('代理服务器错误:', error.message);

        // 区分不同类型的错误
        if (error.code === 'ENOTFOUND') {
            res.status(503).json({
                error: '网络连接失败',
                message: '无法连接到API服务器，请检查网络连接'
            });
        } else if (error.name === 'AbortError' || error.message.includes('timeout')) {
            res.status(408).json({
                error: '请求超时',
                message: 'API调用超时，请稍后重试'
            });
        } else {
            res.status(500).json({
                error: '代理服务器错误',
                message: error.message
            });
        }
    }
});

// 健康检查
app.get('/health', (req, res) => {
    res.json({ status: 'ok', message: '代理服务器运行正常' });
});

app.listen(PORT, () => {
    console.log(`🚀 代理服务器运行在 http://localhost:${PORT}`);
    console.log(`📡 API代理地址: http://localhost:${PORT}/api/chat`);
});